package com.baitengsoft.patentservicemonitor.job.redis.service.impl;

import com.baitengsoft.patentservicemonitor.job.redis.service.IRedisHashService;
import com.sun.corba.se.spi.ior.ObjectKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Consumer;

/**
 * @author wangze
 * @date 2018-08-26 19:13.
 **/
@Component
public class RedisHashImpl implements IRedisHashService {
    @Autowired
    private HashOperations<String, String, Object> hashOperations;

    @Override
    public String get(String key, String hKey) {

        return (String) hashOperations.get(key, hKey);
    }

    @Override
    public void set(String key, Map<String, Object> map) {
        hashOperations.putAll(key, map);

    }

    @Override
    public void set(String key, String hkey, Object value) {
        hashOperations.put(key, hkey, value);
    }

    /**
     * @param key
     * @description 获取键(key)下面的所有属性
     */
    @Override
    public Set<String> getKeys(String key) {
        Set<String> set = hashOperations.keys(key);
        return set;
    }


    /**
     * @param key
     * @param hashKeys
     * @description 删除指定的键（key）下面的属性（hashKeys）
     */
    @Override
    public void delete(String key, Object... hashKeys) {
        hashOperations.delete(key, hashKeys);
    }

    @Override
    public List<Object> getValues(String key) {
        return hashOperations.values(key);
    }


    @Override
    public long size(String key) {
        return this.hashOperations.size(key);
    }

    @Override
    public Map<String, Object> pagination(String key, Consumer<String> action) {
        Map<String, Object> map = new HashMap<>();
        ScanOptions sc = ScanOptions.scanOptions().match("*").count(1000).build();
        Cursor<Map.Entry<String, Object>> cursor = hashOperations.scan(key, sc);
        if (cursor.isClosed()) {
            return null;
        }
        while (cursor.hasNext()) {
            Map.Entry<String, Object> entry = cursor.next();
            map.put(entry.getKey(), entry.getValue());
            action.accept(entry.getKey());
        }
        System.out.println(map.size());
        return map;
    }
}
